<?php

	require_once(EBUILDY_PATH."/lib/phpsvnclient/phpsvnclient.php");

	class EbSVNUpdate
	{
		private $svnClient;
		
		var $ebuildySVNPath = '/trunk/ebuildy/ebuildy/';
		var $themesSVNPath = '/trunk/ebuildy/themes/';
		var $modulesSVNPath = '/trunk/ebuildy/modules/';
		
		var $listSVNPaths;
		var $listRealPaths;
		
		public function __construct($url)
		{
			$this->listSVNPaths = array($this->ebuildySVNPath,$this->themesSVNPath,$this->modulesSVNPath);
			$this->listRealPaths = array(EBUILDY_PATH,MODULES_PATH,THEMES_PATH);
			$this->svnClient = new phpsvnclient($url);
		}
		
		public function getRemoteFiles($path = 0)
		{
			$buffer = $this->svnClient->getDirectoryTree($this->listSVNPaths[$path]);
			
			foreach ($buffer AS &$item)
			{
				$item['last-mod'] = strtotime($item['last-mod']);
				$item['path'] = substr($item['path'],strlen($this->listSVNPaths[$path]) - 1);
			}
			
			return $buffer;
		}
		
		public function getLocalFiles($path_type = 0,$path = null)
		{
			if (is_null($path)) $path = $this->listRealPaths[$path_type];
			
			$path = rtrim(str_replace("\\", "/", $path), '/') . '/';
			$dir = dir($path);
			$buffer = array();
												
			while (false !== ($entry = $dir->read())) 
			{
				if ($entry != "." && $entry != ".." && $entry != '.svn')
				{
					$item = array();
					$item['path'] = substr($path.$entry,strlen($this->listRealPaths[$path_type]));
					$item['last-mod'] = filemtime($path.$entry);
										
					if (is_dir($path.$entry))
					{
						$buffer = array_merge($buffer,$this->getLocalFiles($path_type,$path.$entry));
						$item['type'] = 'directory';
					}
					else
					{
						$item['type'] = 'file';
						$buffer []= $item;
					}
				}
			}
			
			$dir->close();
			
			return $buffer;
		}				

		public function getUpdatedFiles()
		{
			$buffer = array();
			
			$remote = $this->getRemoteFiles();
			$local = $this->getLocalFiles();
			
			foreach ($remote AS $remoteFile)
			{
				foreach ($local AS $localFile)
				{
					if ($localFile['path'] == $remoteFile['path']
					&& $localFile['last-mod'] < $remoteFile['last-mod'])
					{
						$buffer []= (object) array('path' => $localFile['path'],'local' => $localFile['last-mod'],'remote' => $remoteFile['last-mod'],'updated' => $remoteFile['last-mod'] - $localFile['last-mod']);
					}
				}
			}
			
			return $buffer;
		}
		
		public function updateFile($path_index,$path)
		{
			$fileContent = $this->svnClient->getFile($this->listSVNPaths[$path_index].$path);
			
			return file_put_contents($this->listRealPaths[$path_index].'/'.$path,$fileContent);
		}
	}